package cn.com.edaily.auth.utils;

import cn.com.edaily.common.RsaKey;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Component
public class RsaKeyFactory implements InitializingBean, Serializable {

	private static final long serialVersionUID = 6697909247442147683L;

	@Value("${rsaKey.num.of.rsaKeyFacatory}")
	private Integer numOfRsaKey;

	private static volatile List<RsaKey> keyList = new ArrayList<RsaKey>();  //用于封装随机产生的公钥与私钥

	@Override
	public void afterPropertiesSet() throws Exception {
		// KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		// 初始化密钥对生成器，密钥大小为96-1024位
		keyPairGen.initialize(1024, new SecureRandom());
		for (int i = 0; i < numOfRsaKey; i++) {
			// 生成一个密钥对，保存在keyPair中
			KeyPair keyPair = keyPairGen.generateKeyPair();
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
			String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
			// 得到私钥字符串
			String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
			RsaKey rsaKey = new RsaKey(publicKeyString, privateKeyString);
			// 将公钥和私钥保存到list
			keyList.add(rsaKey);
		}
	}

	/**
	 * @Description: 随机获取一对rsa密钥
	 * @author chenwb
	 * @date 2020/1/30 15:57
	 * @return RsaKey
	 */
	public static RsaKey getInstance() {
		Integer keyIndex = new Random().nextInt(keyList.size());
		return new RsaKey(keyList.get(keyIndex).getPublicKey(), keyIndex);
	}

	/**
	 * 获取keyList
	 *
	 * @return keyList
	 */
	public static List<RsaKey> getKeyList() {
		return keyList;
	}

}
